from django.shortcuts import render

# Create your views here.
import uuid
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from app01 import models

class AuthView(APIView):
    '''用户登录认证'''

    def post(self,request,*args,**kwargs):
        print(request.data)
        username = request.data.get("username")
        password = request.data.get("password")

        user_object = models.UserInfo.objects.filter(username=username,password=password).first()
        if not user_object:
            return Response({"code":1000,"data":"用户名或密码错误"})

        token = str(uuid.uuid4())

        user_object.token = token
        user_object.save()

        return Response({"code":200,"data":{"token":token,"name":username}})



class MyAuthenication(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get("token")
        if not token:

            # 场景1:没有token抛出异常认证失败
            # raise AuthenticationFailed({"code":1001,"error":"认证失败"})

            # 场景2:没有token，反回None
            return None
        user_object = models.UserInfo.objects.filter(token=token).first()
        if not user_object:
            raise AuthenticationFailed({"code":1001,"error":"认证失败"})

        return user_object,token

    def authenticate_header(self, request):
        return 'Bearer realm="API"'




class OrderView(APIView):
    authentication_classes = [MyAuthenication,]

    def get(self,request,*args,**kwargs):
        print(request.user)
        # print(request.auth)

        if request.user:
            return Response({"code":0,"data":{"user":request.user.username,"list":[11,22,33]}})
        return Response({"code":200,"data":{"user":None,"list":[44,55,66]}})

